package milu.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.io.IOUtils;
import org.apache.commons.fileupload.FileUploadException;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.users.*;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import milu.models.*;
import milu.*;

public class EditRecipe extends HttpServlet {
    public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

        MyUser myUser = (MyUser)request.getAttribute("myUser");
        if(myUser == null) {
            response.sendRedirect("/");
            return;
        }

        String[] segments = request.getRequestURI().split("/");
        String recipeId = null;
        if(segments.length >= 3)
            recipeId = segments[2];

        // check if this user owns this recipe 

        // find the recipe
        PersistenceManager pm = Datastore.getPersistenceManager();
        Key k = KeyFactory.createKey(Recipe.class.getSimpleName(), Long.parseLong(recipeId));
        Recipe recipe = pm.getObjectById(Recipe.class, k);

        // if this recipe doesn't equal the current user that is logged in
        // dont let this person edit
        if(!recipe.getUserKey().equals(myUser.getKey())) {
            response.sendRedirect("/");
            return;
        }

        request.setAttribute("recipe", recipe);
        request.getRequestDispatcher("/add.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    }

}
